jQuery(document).ready(
    function () {
    	initPage()
    });


function initPage(){
	let url = location.search;
	let Request = new Object();
	Request = GetRequest(url);
	let temp = 0;
	$.ajax({
        url: "goodsinfo.php",  
        type: "POST",
        dataType: "json",
        error: function(){  
            alert('Error goodsinfo.php');  
        },  
        success: function(res){//如果调用php成功 
        	let data;   
	        $.each(res,function(index,value){
				if (value.id==Request.id){
					data = value;
				}
			});
            initHeader(data);//加载商品商品主要标题选购部分标题的信息
			initMainImg(data);//加载商品主图
			initPriceInfo(data);//加载价格信息
			initTimerCount(data);//加载倒计时信息
			initDetailImg(data);//加载商品详细信息
			initServiceInfo(data);
			//initItemChooseInfo();//加载商品选购信息
			temp ++;
			if (temp===2){
				countPrice();
			}
			
        }
    });
	$.ajax({
        url: "styleinfo.php",  
        type: "POST",
        dataType: "json",
        error: function(){  
            alert('Error styleinfo.php');  
        },  
        success: function(res){//如果调用php成功    
        	let data=[];
        	let datai=0;  
	        $.each(res,function(index,value){
				if (value.goods_id==Request.id){
					data[datai++] = value;
				}
			});
        	initItemChooseInfo(data);//加载商品选购信息        
            temp ++;
			if (temp===2){
				countPrice();
			}
			
			
        }
    });
	setup();//加载地区选择控件
}
//从链接中获取参数
function GetRequest(url) {
	  var theRequest = new Object();
	  if (url.indexOf("?") != -1) {
	    var str = url.substr(1);
	    strs = str.split("&");
	    for(var i = 0; i < strs.length; i ++) {
	      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
	    }
	  }
	  return theRequest;
}

/*
加载页面头部
商品主要标题
选购部分标题
的信息
date = {
	name:  				商品名称
	sellInfo:["",""] 	商品销售折扣优惠信息
	introduce: 			商品介绍
}
 */

function initHeader(res){
	$("title").append(res.name);
	let headerHtml = `<h1>${res.name}`;
	if ("sellInfo" in res &&res.sellInfo){
		let data = res.sellInfo.split("-");
		$.each(data,function(index,value){
			headerHtml += `<span class="akmall-badge">${value}</span>`;
		
		});
	}
	
	headerHtml += `</h1>`;
	$(".header").append(headerHtml);
	let titleHtml =`<h1>${res.name}</h1><p>${res.introduce}</p>`
	$(".akmall-content-title").append(titleHtml);
	let orderTitleHtml = `<i class="icon-cart"></i>${res.name}`;
	$(".akmall-title-order").append(orderTitleHtml);


}

/*
加载商品主要图片
data = "";
 */
function initMainImg(data){

	//let res = "https://ws1.sinaimg.cn/large/e468fffagy1fryg0aaavxj20ly0hyag3.jpg";
	let res = data.mainImg;
	let html = `<img src="${res}" class="image"/>`
	$(".show-image").append(html);
}

/*
加载售价与相关信息
data = {
	symbol:"￥",   		价格单位
	currentPrice:99.8,  现价
	originalPrice:230,	原价
	salenum:1314,		已售数量
}
 */

function initPriceInfo(res){
	
	let html = `<span class="symbol">${res.symbol}</span>
				<span class="current-price">${res.currentPrice}</span>
				<span class="group">
					<del class="original-price">
	  						${res.originalPrice}元
					</del>
					<span class="salenum">已售:${res.salenum}</span>
				</span>`;



	$(".price").append(html);
}
/*
加载倒计时
data = 2321		倒数时间 单位秒
 */
function initTimerCount(res){
	if (!"deadline" in res) return;
	if (!res.deadline) return;
	let t1 = res.deadline;
	let d1 = t1.replace(/\-/g, "/");
	let date1 = new Date(d1);
	var d2 = new Date();
	let times = parseInt((date1-d2)/1000); 
	if (times){
		let html = 
			`<p class="tt">
				活動倒計時
			</p>
			<div id="akmall-timer" class="akmall-timer">
				<strong><span class="akmallDay"></span>
				<span class="akmallHour">00</span>
				<span>:</span>
				<span class="akmallMinute">00</span>
				<span>:</span>
				<span class="akmallSecond">00</span></strong>
			</div>`;
		$(".timer").append(html);
		let timer=null;
	  	timer=setInterval(function(){
	    var day=0,
	      hour=0,
	      minute=0,
	      second=0;//时间默认值
	    if(times > 0){
	      //day = Math.floor(times / (60 * 60 * 24));
	      hour = Math.floor(times / (60 * 60));
	      minute = Math.floor(times / 60) - (day * 24 * 60) - (hour * 60);
	      second = Math.floor(times) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
	    }
	    //day = day<=9?'0' + day:day;
	    hour = hour<=9?'0' + hour:hour;
	    minute = minute<=9?'0' + minute:minute;
	    second = second<=9?'0' + second:second;
		//$(".akmallDay").html(day);
		$(".akmallHour").html(hour);
		$(".akmallMinute").html(minute);
		$(".akmallSecond").html(second);
	    
	    times--;
	  },1000);
	  if(times<=0){
	    clearInterval(timer);
	  }

	}
}
/*
加载商品提供的服务信息
data = ["",""]; 	商品提供的服务信息
 */
function initServiceInfo(res){
	if (("ServiceInfo" in res)&&res.ServiceInfo){
		let data = res.ServiceInfo.split("-");
		let info = data;
		$.each(info,function(index,value){
			let html  = `<span class="comfirmpic">${value}</span>`;
			$(".baoyou").append(html);
		});
	}
	
}

/*
加载商品详细信息图片
data = "";	图片路径
 */
function initDetailImg(data){
	let res = data.DetailImg;
	//let res = "https://ws1.sinaimg.cn/large/e468fffagy1fpto5jnie6j20ly0ys45q.jpg";
	let html = `<img src="${res}" class="image"/>`
	$(".detailImg").append(html);
}

function addNum(n){
	let quantiryInput = $("input[name=quantity]");
	let num = parseInt(quantiryInput.val());
	num+=n;
	quantiryInput.val(num);
	countPrice();
}

function countPrice(){
	let totalPrice = parseInt($(".total-price").text());
	let productStyle = $("input[name=productChoose]:checked");
	let singlePrice = parseInt(productStyle.attr("price"));
	let quantiryInput = $("input[name=quantity]");
	let num = parseInt(quantiryInput.val());
	num = num<0?0:num;
	num = num?num:0;
	quantiryInput.val(num);
	totalPrice = num*singlePrice;
	$('.total-price').html(totalPrice);
	
}
$("#mall-submit").click(function(){
	$(" .form-tips").html('');
	$(".akmall-box input").removeClass("error");
	let error=0;
	let productStyle = $("input[name=productChoose]:checked").val();
	let quantiryInput = $("input[name=quantity]");
	let num = parseInt(quantiryInput.val());
	let price = parseInt($(".total-price").text());
	let name = $("input[name=name]").val();
	if(!name){
		$(".rows-id-name input").addClass("error");
		$(".rows-id-name .form-tips").addClass('error');
		$(".rows-id-name .form-tips").html('请输入姓名');
		error++;
	}
	let mobile = $("input[name=mobile]").val();
	let phoneReg = /[1-9][0-9]{6,}/;
	if(!mobile){
		$(".rows-id-mobile input").addClass("error");
		$(".rows-id-mobile .form-tips").addClass('error');
		$(".rows-id-mobile .form-tips").html('请输入收货电话');
		error++;
	}else if (!phoneReg.test(mobile)) {  
	    $(".rows-id-mobile input").addClass("error");
		$(".rows-id-mobile .form-tips").addClass('error');
		$(".rows-id-mobile .form-tips").html('请输入有效的电话号码');
		error++;
	}
	let regionco = $("select[name=regionco]").val();
	let regionp = $("select[name=regionp]").val();
	let regionci = $("select[name=regionci]").val();
	if((!regionco)||(!regionp)||(!regionci)){
		$(".rows-id-region .rows-params").addClass('error');
		$(".rows-id-region .form-tips").addClass('error');
		$(".rows-id-region .form-tips").html('请选择收货地区');
		error++;
	}
	let region=`${regionco}-${regionp}-${regionci}`
	let address = $("input[name=address]").val();
	if(!address){
		$(".rows-id-address input").addClass("error");
		$(".rows-id-address .form-tips").addClass('error');
		$(".rows-id-address .form-tips").html('请输入详细地址');
		error++;
	}
	let mail = $("input[name=mail]").val();
	let mainReg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
	if (mail&&(!mainReg.test(mail))) {  
	    $(".rows-id-mail input").addClass("error");
		$(".rows-id-mail .form-tips").addClass('error');
		$(".rows-id-mail .form-tips").html('请输入有效的电子邮箱');
		error++;
	}
	let remark = $("textarea[name=remark]").val();

	if (error){
		location.hash=""
		location.hash="#akmall-box-2";
		return
	};
	let data = {
		style:productStyle,
		price:price,
		num:num,
		name:name,
		mobile:mobile,
		region:region,
		address:address,
		mail:mail,
		remark:remark,
	}
	$.ajax({
        url: "orderInsert.php",  
        type: "GET",
        dataType: "json",
        data:data,
        error: function(res){  
            showPage();
        },  
        success: function(res){//如果调用php成功            
            showPage();
        }
    });




	})
function showPage(){
	$(".main-box").empty();
	$.ajax({
        url: "ordersinfo.php",  
        type: "POST",
        dataType: "json",
        error: function(res){  

        },  
        success: function(res){
        	let data = res[res.length-1];
        	let html = `<div class="header"><h1>订单提交成功</h1></div>`;
			let htmlinfo = `<div class="akmall-content-title">
				<p>商品信息：${data.style}</p>
				<p>订购数量：${data.num}</p>
				<p>商品总价：${data.price}</p>
				<p>姓名：${data.name}</p>
				<p>联系电话：${data.mobile}</p>
				<p>收货地区：${data.region}</p>
				<p>详细地址：${data.address}</p>
				<p>联系邮件：${data.mail}</p>
				<p>备注：${data.remark}</p>

				</div>`
			$(".main-box").append(html+htmlinfo);	
        }
    });
	

}


function initItemChooseInfo(data){

	$.each(data,function(index,value){
		if (!index){
		let html  = `<label class="product akmall-params akmall-radio active " title="${value.style}" name="${value.style}" onclick="countPrice();">
						<p class="item-desc">
							<input type="radio" class="countPrice" name="productChoose" value="${value.style}" price="${value.price}" checked=""/>${value.style}
						</p>
					</label>`;
		$(".chooseProduct").append(html);
	}else {
		let html  = `<label  class="product akmall-params akmall-radio" title="${value.style}" name="${value.style}" onclick="countPrice();">
						<p class="item-desc">
							<input type="radio" class="countPrice" name="productChoose" value="${value.style}" price="${value.price}" checked=""/>${value.style}
						</p>
					</label>`;
		$(".chooseProduct").append(html);
	}
		
	});

	$(".chooseProduct .product").click(function(){
		$(".chooseProduct .product").removeClass("active");
		$(this).addClass("active");
		$(".productStyle").empty();
		let name =$(this).attr("name");
	})
}

function test(){
	let data = [{style:"黑框眼镜-男士",price:101},
				{style:"黑框眼镜-女士",price:102},
				{style:"白框眼镜-女士",price:104},
				{style:"白框眼镜-男士",price:105},
				{style:"白框眼镜-儿童",price:106},
				{style:"彩框眼镜-女士",price:107},
				{style:"彩框眼镜-男士",price:108},];
	let res =[];
	$.each(data,function(index,value){
		let style = value.style.split("-");
		$.each(style,function(index2,value2){
			let str = `style${index}`;
			let temp = 0;
			$.each(res,function(index3,value3){
				if ( str in res[index3]){
					if (res[index3][str]===value2){
						
					}
					
				}
			
			});
			
		});
	});



}
/*
加载商品选购信息 	
 
function initItemChooseInfo(){
	let res = [{
		product:"黑框彩镜",
		style:[{
			name:"男士",
			price:100,
		},{
			name:"女士",
			price:100,
		},{
			name:"儿童",
			price:100,
		}]
	},
	{
		product:"黑框墨镜",
		style:[{
			name:"男士",
			price:120,
		},{
			name:"女士",
			price:130,
		},]
	},
	{
		product:"白框彩镜",
		style:[{
			name:"男士",
			price:120,
		},{
			name:"女士",
			price:130,
		},{
			name:"儿童",
			price:100,
		}]
	}]
	$.each(res,function(index,value){
		if (!index){
		let html  = `<label class="product akmall-params akmall-radio active " title="${value.product}" name="${value.product}" onclick="countPrice();">
						<p class="item-desc">
							<input type="radio" class="countPrice" name="productChoose" value="${value.product}" checked=""/>${value.product}
						</p>
					</label>`;
		$(".chooseProduct").append(html);
		$.each(value.style,function(index2,value2){
			if (!index2){
				let html  = `<label class="akmall-group akmall-params akmall-radio productStyleLabel active" onclick="countPrice();">
								<span class="akmall-group-box">
									<input class="radio-0 productStyleRadio countPrice" name="productStyle" price="${value2.price}" type="radio"  value="${value2.name}" checked=""/>
									<label class="selected-icon" ></label>
								</span>${value2.name}
							</label>`;
				$(".productStyle").append(html);
			}else {
					let html  = `<label class="akmall-group akmall-params akmall-radio productStyleLabel" onclick="countPrice();">
									<span class="akmall-group-box">
										<input class="radio-0 productStyleRadio countPrice" name="productStyle" price="${value2.price}" type="radio" value="${value2.name}" />
										<label class="selected-icon"></label>
									</span>${value2.name}
								</label>`;
					$(".productStyle").append(html);
			}
		
	});
	}else {
		let html  = `<label  class="product akmall-params akmall-radio" title="${value.product}" name="${value.product}" onclick="countPrice();">
						<p class="item-desc">
							<input type="radio" class="countPrice" name="productChoose" value="${value.product}" checked=""/>${value.product}
						</p>
					</label>`;
		$(".chooseProduct").append(html);
	}
		
	});
	$(".chooseProduct .product").click(function(){
		$(".chooseProduct .product").removeClass("active");
		$(this).addClass("active");
		$(".productStyle").empty();
		let name =$(this).attr("name");
			$.each(res,function(index,value){
			if (value.product==name){
				$.each(value.style,function(index2,value2){
					if (!index2){
						let html  = `<label class="akmall-group akmall-params akmall-radio productStyleLabel active" onclick="countPrice();">
										<span class="akmall-group-box">
											<input class="radio-0 productStyleRadio countPrice" name="productStyle" price="${value2.price}" type="radio" value="${value2.name}" checked=""/>
											<label class="selected-icon"></label>
										</span>${value2.name}
									</label>`;
						$(".productStyle").append(html);
					}else {
							let html  = `<label class="akmall-group akmall-params akmall-radio productStyleLabel" onclick="countPrice();">
											<span class="akmall-group-box">
												<input class="radio-0 productStyleRadio countPrice" name="productStyle" price="${value2.price}"  type="radio" value="${value2.name}" />
												<label class="selected-icon"></label>
											</span>${value2.name}
										</label>`;
							$(".productStyle").append(html);
					}
				
				});
			}
			
		});
		$(".productStyle .productStyleLabel").click(function(){
			$(".productStyle .productStyleLabel").removeClass("active");
			$(this).addClass("active");

		})

	})
	$(".productStyle .productStyleLabel").click(function(){
		$(".productStyle .productStyleLabel").removeClass("active");
		$(this).addClass("active");

	})
	

}
*/